3 namespace MediaWiki\Session
;
13 * @covers MediaWiki\Session\SessionManager
15 class SessionManagerTest
extends MediaWikiTestCase
{
17 protected $config, $logger, $store;
19 protected function getManager() {
20 \ObjectCache
::$instances['testSessionStore'] = new TestBagOStuff();
21 $this->config
= new \
HashConfig( [
22 'LanguageCode' => 'en',
23 'SessionCacheType' => 'testSessionStore',
24 'ObjectCacheSessionExpiry' => 100,
25 'SessionProviders' => [
26 [ 'class' => 'DummySessionProvider' ],
29 $this->logger
= new \
TestLogger( false, function ( $m ) {
30 return substr( $m, 0, 15 ) === 'SessionBackend ' ?
null : $m;
32 $this->store
= new TestBagOStuff();
34 return new SessionManager( [
35 'config' => $this->config
,
36 'logger' => $this->logger
,
37 'store' => $this->store
,
41 protected function objectCacheDef( $object ) {
42 return [ 'factory' => function () use ( $object ) {
47 public function testSingleton() {
48 $reset = TestUtils
::setSessionManagerSingleton( null );
50 $singleton = SessionManager
::singleton();
51 $this->assertInstanceOf( SessionManager
::class, $singleton );
52 $this->assertSame( $singleton, SessionManager
::singleton() );
55 public function testGetGlobalSession() {
56 $context = \RequestContext
::getMain();
58 if ( !PHPSessionHandler
::isInstalled() ) {
59 PHPSessionHandler
::install( SessionManager
::singleton() );
61 $rProp = new \
ReflectionProperty( PHPSessionHandler
::class, 'instance' );
62 $rProp->setAccessible( true );
63 $handler = \TestingAccessWrapper
::newFromObject( $rProp->getValue() );
64 $oldEnable = $handler->enable
;
65 $reset[] = new \
ScopedCallback( function () use ( $handler, $oldEnable ) {
66 if ( $handler->enable
) {
67 session_write_close();
69 $handler->enable
= $oldEnable;
71 $reset[] = TestUtils
::setSessionManagerSingleton( $this->getManager() );
73 $handler->enable
= true;
74 $request = new \
FauxRequest();
75 $context->setRequest( $request );
76 $id = $request->getSession()->getId();
79 $session = SessionManager
::getGlobalSession();
80 $this->assertSame( $id, $session->getId() );
82 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
83 $session = SessionManager
::getGlobalSession();
84 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $session->getId() );
85 $this->assertSame( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', $request->getSession()->getId() );
87 session_write_close();
88 $handler->enable
= false;
89 $request = new \
FauxRequest();
90 $context->setRequest( $request );
91 $id = $request->getSession()->getId();
94 $session = SessionManager
::getGlobalSession();
95 $this->assertSame( $id, $session->getId() );
97 session_id( 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
98 $session = SessionManager
::getGlobalSession();
99 $this->assertSame( $id, $session->getId() );
100 $this->assertSame( $id, $request->getSession()->getId() );
103 public function testConstructor() {
104 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
105 $this->assertSame( $this->config
, $manager->config
);
106 $this->assertSame( $this->logger
, $manager->logger
);
107 $this->assertSame( $this->store
, $manager->store
);
109 $manager = \TestingAccessWrapper
::newFromObject( new SessionManager() );
110 $this->assertSame( \RequestContext
::getMain()->getConfig(), $manager->config
);
112 $manager = \TestingAccessWrapper
::newFromObject( new SessionManager( [
113 'config' => $this->config
,
115 $this->assertSame( \ObjectCache
::$instances['testSessionStore'], $manager->store
);
118 'config' => '$options[\'config\'] must be an instance of Config',
119 'logger' => '$options[\'logger\'] must be an instance of LoggerInterface',
120 'store' => '$options[\'store\'] must be an instance of BagOStuff',
121 ] as $key => $error ) {
123 new SessionManager( [ $key => new \stdClass
] );
124 $this->fail( 'Expected exception not thrown' );
125 } catch ( \InvalidArgumentException
$ex ) {
126 $this->assertSame( $error, $ex->getMessage() );
131 public function testGetSessionForRequest() {
132 $manager = $this->getManager();
133 $request = new \
FauxRequest();
134 $request->unpersist1
= false;
135 $request->unpersist2
= false;
139 $idEmpty = 'empty-session-------------------';
141 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
143 [ 'provideSessionInfo', 'newSessionInfo', '__toString', 'describe', 'unpersistSession' ]
146 $provider1 = $providerBuilder->getMock();
147 $provider1->expects( $this->any() )->method( 'provideSessionInfo' )
148 ->with( $this->identicalTo( $request ) )
149 ->will( $this->returnCallback( function ( $request ) {
150 return $request->info1
;
152 $provider1->expects( $this->any() )->method( 'newSessionInfo' )
153 ->will( $this->returnCallback( function () use ( $idEmpty, $provider1 ) {
154 return new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
155 'provider' => $provider1,
161 $provider1->expects( $this->any() )->method( '__toString' )
162 ->will( $this->returnValue( 'Provider1' ) );
163 $provider1->expects( $this->any() )->method( 'describe' )
164 ->will( $this->returnValue( '#1 sessions' ) );
165 $provider1->expects( $this->any() )->method( 'unpersistSession' )
166 ->will( $this->returnCallback( function ( $request ) {
167 $request->unpersist1
= true;
170 $provider2 = $providerBuilder->getMock();
171 $provider2->expects( $this->any() )->method( 'provideSessionInfo' )
172 ->with( $this->identicalTo( $request ) )
173 ->will( $this->returnCallback( function ( $request ) {
174 return $request->info2
;
176 $provider2->expects( $this->any() )->method( '__toString' )
177 ->will( $this->returnValue( 'Provider2' ) );
178 $provider2->expects( $this->any() )->method( 'describe' )
179 ->will( $this->returnValue( '#2 sessions' ) );
180 $provider2->expects( $this->any() )->method( 'unpersistSession' )
181 ->will( $this->returnCallback( function ( $request ) {
182 $request->unpersist2
= true;
185 $this->config
->set( 'SessionProviders', [
186 $this->objectCacheDef( $provider1 ),
187 $this->objectCacheDef( $provider2 ),
190 // No provider returns info
191 $request->info1
= null;
192 $request->info2
= null;
193 $session = $manager->getSessionForRequest( $request );
194 $this->assertInstanceOf( Session
::class, $session );
195 $this->assertSame( $idEmpty, $session->getId() );
196 $this->assertFalse( $request->unpersist1
);
197 $this->assertFalse( $request->unpersist2
);
199 // Both providers return info, picks best one
200 $request->info1
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, [
201 'provider' => $provider1,
202 'id' => ( $id1 = $manager->generateSessionId() ),
206 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, [
207 'provider' => $provider2,
208 'id' => ( $id2 = $manager->generateSessionId() ),
212 $session = $manager->getSessionForRequest( $request );
213 $this->assertInstanceOf( Session
::class, $session );
214 $this->assertSame( $id2, $session->getId() );
215 $this->assertFalse( $request->unpersist1
);
216 $this->assertFalse( $request->unpersist2
);
218 $request->info1
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, [
219 'provider' => $provider1,
220 'id' => ( $id1 = $manager->generateSessionId() ),
224 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, [
225 'provider' => $provider2,
226 'id' => ( $id2 = $manager->generateSessionId() ),
230 $session = $manager->getSessionForRequest( $request );
231 $this->assertInstanceOf( Session
::class, $session );
232 $this->assertSame( $id1, $session->getId() );
233 $this->assertFalse( $request->unpersist1
);
234 $this->assertFalse( $request->unpersist2
);
237 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
238 'provider' => $provider1,
239 'id' => ( $id1 = $manager->generateSessionId() ),
241 'userInfo' => UserInfo
::newAnonymous(),
244 $request->info2
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
245 'provider' => $provider2,
246 'id' => ( $id2 = $manager->generateSessionId() ),
248 'userInfo' => UserInfo
::newAnonymous(),
252 $manager->getSessionForRequest( $request );
253 $this->fail( 'Expcected exception not thrown' );
254 } catch ( \OverflowException
$ex ) {
255 $this->assertStringStartsWith(
256 'Multiple sessions for this request tied for top priority: ',
259 $this->assertCount( 2, $ex->sessionInfos
);
260 $this->assertContains( $request->info1
, $ex->sessionInfos
);
261 $this->assertContains( $request->info2
, $ex->sessionInfos
);
263 $this->assertFalse( $request->unpersist1
);
264 $this->assertFalse( $request->unpersist2
);
267 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
268 'provider' => $provider2,
269 'id' => ( $id1 = $manager->generateSessionId() ),
273 $request->info2
= null;
275 $manager->getSessionForRequest( $request );
276 $this->fail( 'Expcected exception not thrown' );
277 } catch ( \UnexpectedValueException
$ex ) {
279 'Provider1 returned session info for a different provider: ' . $request->info1
,
283 $this->assertFalse( $request->unpersist1
);
284 $this->assertFalse( $request->unpersist2
);
286 // Unusable session info
287 $this->logger
->setCollect( true );
288 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
289 'provider' => $provider1,
290 'id' => ( $id1 = $manager->generateSessionId() ),
292 'userInfo' => UserInfo
::newFromName( 'UTSysop', false ),
295 $request->info2
= new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
296 'provider' => $provider2,
297 'id' => ( $id2 = $manager->generateSessionId() ),
301 $session = $manager->getSessionForRequest( $request );
302 $this->assertInstanceOf( Session
::class, $session );
303 $this->assertSame( $id2, $session->getId() );
304 $this->logger
->setCollect( false );
305 $this->assertTrue( $request->unpersist1
);
306 $this->assertFalse( $request->unpersist2
);
307 $request->unpersist1
= false;
309 $this->logger
->setCollect( true );
310 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
311 'provider' => $provider1,
312 'id' => ( $id1 = $manager->generateSessionId() ),
316 $request->info2
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
317 'provider' => $provider2,
318 'id' => ( $id2 = $manager->generateSessionId() ),
320 'userInfo' => UserInfo
::newFromName( 'UTSysop', false ),
323 $session = $manager->getSessionForRequest( $request );
324 $this->assertInstanceOf( Session
::class, $session );
325 $this->assertSame( $id1, $session->getId() );
326 $this->logger
->setCollect( false );
327 $this->assertFalse( $request->unpersist1
);
328 $this->assertTrue( $request->unpersist2
);
329 $request->unpersist2
= false;
331 // Unpersisted session ID
332 $request->info1
= new SessionInfo( SessionInfo
::MAX_PRIORITY
, [
333 'provider' => $provider1,
334 'id' => ( $id1 = $manager->generateSessionId() ),
335 'persisted' => false,
336 'userInfo' => UserInfo
::newFromName( 'UTSysop', true ),
339 $request->info2
= null;
340 $session = $manager->getSessionForRequest( $request );
341 $this->assertInstanceOf( Session
::class, $session );
342 $this->assertSame( $id1, $session->getId() );
343 $this->assertTrue( $request->unpersist1
); // The saving of the session does it
344 $this->assertFalse( $request->unpersist2
);
346 $this->assertTrue( $session->isPersistent(), 'sanity check' );
349 public function testGetSessionById() {
350 $manager = $this->getManager();
352 $manager->getSessionById( 'bad' );
353 $this->fail( 'Expected exception not thrown' );
354 } catch ( \InvalidArgumentException
$ex ) {
355 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
358 // Unknown session ID
359 $id = $manager->generateSessionId();
360 $session = $manager->getSessionById( $id, true );
361 $this->assertInstanceOf( Session
::class, $session );
362 $this->assertSame( $id, $session->getId() );
364 $id = $manager->generateSessionId();
365 $this->assertNull( $manager->getSessionById( $id, false ) );
367 // Known but unloadable session ID
368 $this->logger
->setCollect( true );
369 $id = $manager->generateSessionId();
370 $this->store
->setSession( $id, [ 'metadata' => [
371 'userId' => User
::idFromName( 'UTSysop' ),
372 'userToken' => 'bad',
375 $this->assertNull( $manager->getSessionById( $id, true ) );
376 $this->assertNull( $manager->getSessionById( $id, false ) );
377 $this->logger
->setCollect( false );
380 $this->store
->setSession( $id, [] );
381 $session = $manager->getSessionById( $id, false );
382 $this->assertInstanceOf( Session
::class, $session );
383 $this->assertSame( $id, $session->getId() );
385 // Store isn't checked if the session is already loaded
386 $this->store
->setSession( $id, [ 'metadata' => [
387 'userId' => User
::idFromName( 'UTSysop' ),
388 'userToken' => 'bad',
390 $session2 = $manager->getSessionById( $id, false );
391 $this->assertInstanceOf( Session
::class, $session2 );
392 $this->assertSame( $id, $session2->getId() );
393 unset( $session, $session2 );
394 $this->logger
->setCollect( true );
395 $this->assertNull( $manager->getSessionById( $id, true ) );
396 $this->logger
->setCollect( false );
398 // Failure to create an empty session
399 $manager = $this->getManager();
400 $provider = $this->getMockBuilder( 'DummySessionProvider' )
401 ->setMethods( [ 'provideSessionInfo', 'newSessionInfo', '__toString' ] )
403 $provider->expects( $this->any() )->method( 'provideSessionInfo' )
404 ->will( $this->returnValue( null ) );
405 $provider->expects( $this->any() )->method( 'newSessionInfo' )
406 ->will( $this->returnValue( null ) );
407 $provider->expects( $this->any() )->method( '__toString' )
408 ->will( $this->returnValue( 'MockProvider' ) );
409 $this->config
->set( 'SessionProviders', [
410 $this->objectCacheDef( $provider ),
412 $this->logger
->setCollect( true );
413 $this->assertNull( $manager->getSessionById( $id, true ) );
414 $this->logger
->setCollect( false );
416 [ LogLevel
::ERROR
, 'Failed to create empty session: {exception}' ]
417 ], $this->logger
->getBuffer() );
420 public function testGetEmptySession() {
421 $manager = $this->getManager();
422 $pmanager = \TestingAccessWrapper
::newFromObject( $manager );
423 $request = new \
FauxRequest();
425 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
426 ->setMethods( [ 'provideSessionInfo', 'newSessionInfo', '__toString' ] );
432 $provider1 = $providerBuilder->getMock();
433 $provider1->expects( $this->any() )->method( 'provideSessionInfo' )
434 ->will( $this->returnValue( null ) );
435 $provider1->expects( $this->any() )->method( 'newSessionInfo' )
436 ->with( $this->callback( function ( $id ) use ( &$expectId ) {
437 return $id === $expectId;
439 ->will( $this->returnCallback( function () use ( &$info1 ) {
442 $provider1->expects( $this->any() )->method( '__toString' )
443 ->will( $this->returnValue( 'MockProvider1' ) );
445 $provider2 = $providerBuilder->getMock();
446 $provider2->expects( $this->any() )->method( 'provideSessionInfo' )
447 ->will( $this->returnValue( null ) );
448 $provider2->expects( $this->any() )->method( 'newSessionInfo' )
449 ->with( $this->callback( function ( $id ) use ( &$expectId ) {
450 return $id === $expectId;
452 ->will( $this->returnCallback( function () use ( &$info2 ) {
455 $provider1->expects( $this->any() )->method( '__toString' )
456 ->will( $this->returnValue( 'MockProvider2' ) );
458 $this->config
->set( 'SessionProviders', [
459 $this->objectCacheDef( $provider1 ),
460 $this->objectCacheDef( $provider2 ),
468 $manager->getEmptySession();
469 $this->fail( 'Expected exception not thrown' );
470 } catch ( \UnexpectedValueException
$ex ) {
472 'No provider could provide an empty session!',
479 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
480 'provider' => $provider1,
481 'id' => 'empty---------------------------',
486 $session = $manager->getEmptySession();
487 $this->assertInstanceOf( Session
::class, $session );
488 $this->assertSame( 'empty---------------------------', $session->getId() );
491 $expectId = 'expected------------------------';
492 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
493 'provider' => $provider1,
499 $session = $pmanager->getEmptySessionInternal( null, $expectId );
500 $this->assertInstanceOf( Session
::class, $session );
501 $this->assertSame( $expectId, $session->getId() );
504 $expectId = 'expected-----------------------2';
505 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
506 'provider' => $provider1,
507 'id' => "un$expectId",
513 $pmanager->getEmptySessionInternal( null, $expectId );
514 $this->fail( 'Expected exception not thrown' );
515 } catch ( \UnexpectedValueException
$ex ) {
517 'MockProvider1 returned empty session info with a wrong id: ' .
518 "un$expectId != $expectId",
524 $expectId = 'expected-----------------------2';
525 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
526 'provider' => $provider1,
532 $pmanager->getEmptySessionInternal( null, $expectId );
533 $this->fail( 'Expected exception not thrown' );
534 } catch ( \UnexpectedValueException
$ex ) {
536 'MockProvider1 returned empty session info with id flagged unsafe',
543 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
544 'provider' => $provider2,
545 'id' => 'empty---------------------------',
551 $manager->getEmptySession();
552 $this->fail( 'Expected exception not thrown' );
553 } catch ( \UnexpectedValueException
$ex ) {
555 'MockProvider1 returned an empty session info for a different provider: ' . $info1,
560 // Highest priority wins
562 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, [
563 'provider' => $provider1,
564 'id' => 'empty1--------------------------',
568 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
569 'provider' => $provider2,
570 'id' => 'empty2--------------------------',
574 $session = $manager->getEmptySession();
575 $this->assertInstanceOf( Session
::class, $session );
576 $this->assertSame( 'empty1--------------------------', $session->getId() );
579 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
1, [
580 'provider' => $provider1,
581 'id' => 'empty1--------------------------',
585 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY +
2, [
586 'provider' => $provider2,
587 'id' => 'empty2--------------------------',
591 $session = $manager->getEmptySession();
592 $this->assertInstanceOf( Session
::class, $session );
593 $this->assertSame( 'empty2--------------------------', $session->getId() );
595 // Tied priorities throw an exception
597 $info1 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
598 'provider' => $provider1,
599 'id' => 'empty1--------------------------',
601 'userInfo' => UserInfo
::newAnonymous(),
604 $info2 = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
605 'provider' => $provider2,
606 'id' => 'empty2--------------------------',
608 'userInfo' => UserInfo
::newAnonymous(),
612 $manager->getEmptySession();
613 $this->fail( 'Expected exception not thrown' );
614 } catch ( \UnexpectedValueException
$ex ) {
615 $this->assertStringStartsWith(
616 'Multiple empty sessions tied for top priority: ',
623 $pmanager->getEmptySessionInternal( null, 'bad' );
624 $this->fail( 'Expected exception not thrown' );
625 } catch ( \InvalidArgumentException
$ex ) {
626 $this->assertSame( 'Invalid session ID', $ex->getMessage() );
629 // Session already exists
630 $expectId = 'expected-----------------------3';
631 $this->store
->setSessionMeta( $expectId, [
632 'provider' => 'MockProvider2',
638 $pmanager->getEmptySessionInternal( null, $expectId );
639 $this->fail( 'Expected exception not thrown' );
640 } catch ( \InvalidArgumentException
$ex ) {
641 $this->assertSame( 'Session ID already exists', $ex->getMessage() );
645 public function testGetVaryHeaders() {
646 $manager = $this->getManager();
648 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
649 ->setMethods( [ 'getVaryHeaders', '__toString' ] );
651 $provider1 = $providerBuilder->getMock();
652 $provider1->expects( $this->once() )->method( 'getVaryHeaders' )
653 ->will( $this->returnValue( [
655 'Bar' => [ 'X', 'Bar1' ],
658 $provider1->expects( $this->any() )->method( '__toString' )
659 ->will( $this->returnValue( 'MockProvider1' ) );
661 $provider2 = $providerBuilder->getMock();
662 $provider2->expects( $this->once() )->method( 'getVaryHeaders' )
663 ->will( $this->returnValue( [
665 'Bar' => [ 'X', 'Bar2' ],
666 'Quux' => [ 'Quux' ],
668 $provider2->expects( $this->any() )->method( '__toString' )
669 ->will( $this->returnValue( 'MockProvider2' ) );
671 $this->config
->set( 'SessionProviders', [
672 $this->objectCacheDef( $provider1 ),
673 $this->objectCacheDef( $provider2 ),
678 'Bar' => [ 'X', 'Bar1', 3 => 'Bar2' ],
679 'Quux' => [ 'Quux' ],
683 $this->assertEquals( $expect, $manager->getVaryHeaders() );
685 // Again, to ensure it's cached
686 $this->assertEquals( $expect, $manager->getVaryHeaders() );
689 public function testGetVaryCookies() {
690 $manager = $this->getManager();
692 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
693 ->setMethods( [ 'getVaryCookies', '__toString' ] );
695 $provider1 = $providerBuilder->getMock();
696 $provider1->expects( $this->once() )->method( 'getVaryCookies' )
697 ->will( $this->returnValue( [ 'Foo', 'Bar' ] ) );
698 $provider1->expects( $this->any() )->method( '__toString' )
699 ->will( $this->returnValue( 'MockProvider1' ) );
701 $provider2 = $providerBuilder->getMock();
702 $provider2->expects( $this->once() )->method( 'getVaryCookies' )
703 ->will( $this->returnValue( [ 'Foo', 'Baz' ] ) );
704 $provider2->expects( $this->any() )->method( '__toString' )
705 ->will( $this->returnValue( 'MockProvider2' ) );
707 $this->config
->set( 'SessionProviders', [
708 $this->objectCacheDef( $provider1 ),
709 $this->objectCacheDef( $provider2 ),
712 $expect = [ 'Foo', 'Bar', 'Baz' ];
714 $this->assertEquals( $expect, $manager->getVaryCookies() );
716 // Again, to ensure it's cached
717 $this->assertEquals( $expect, $manager->getVaryCookies() );
720 public function testGetProviders() {
721 $realManager = $this->getManager();
722 $manager = \TestingAccessWrapper
::newFromObject( $realManager );
724 $this->config
->set( 'SessionProviders', [
725 [ 'class' => 'DummySessionProvider' ],
727 $providers = $manager->getProviders();
728 $this->assertArrayHasKey( 'DummySessionProvider', $providers );
729 $provider = \TestingAccessWrapper
::newFromObject( $providers['DummySessionProvider'] );
730 $this->assertSame( $manager->logger
, $provider->logger
);
731 $this->assertSame( $manager->config
, $provider->config
);
732 $this->assertSame( $realManager, $provider->getManager() );
734 $this->config
->set( 'SessionProviders', [
735 [ 'class' => 'DummySessionProvider' ],
736 [ 'class' => 'DummySessionProvider' ],
738 $manager->sessionProviders
= null;
740 $manager->getProviders();
741 $this->fail( 'Expected exception not thrown' );
742 } catch ( \UnexpectedValueException
$ex ) {
744 'Duplicate provider name "DummySessionProvider"',
750 public function testShutdown() {
751 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
752 $manager->setLogger( new \Psr\Log\
NullLogger() );
754 $mock = $this->getMock( 'stdClass', [ 'shutdown' ] );
755 $mock->expects( $this->once() )->method( 'shutdown' );
757 $manager->allSessionBackends
= [ $mock ];
758 $manager->shutdown();
761 public function testGetSessionFromInfo() {
762 $manager = \TestingAccessWrapper
::newFromObject( $this->getManager() );
763 $request = new \
FauxRequest();
765 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
767 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
768 'provider' => $manager->getProvider( 'DummySessionProvider' ),
771 'userInfo' => UserInfo
::newFromName( 'UTSysop', true ),
774 \TestingAccessWrapper
::newFromObject( $info )->idIsSafe
= true;
775 $session1 = \TestingAccessWrapper
::newFromObject(
776 $manager->getSessionFromInfo( $info, $request )
778 $session2 = \TestingAccessWrapper
::newFromObject(
779 $manager->getSessionFromInfo( $info, $request )
782 $this->assertSame( $session1->backend
, $session2->backend
);
783 $this->assertNotEquals( $session1->index
, $session2->index
);
784 $this->assertSame( $session1->getSessionId(), $session2->getSessionId() );
785 $this->assertSame( $id, $session1->getId() );
787 \TestingAccessWrapper
::newFromObject( $info )->idIsSafe
= false;
788 $session3 = $manager->getSessionFromInfo( $info, $request );
789 $this->assertNotSame( $id, $session3->getId() );
792 public function testBackendRegistration() {
793 $manager = $this->getManager();
795 $session = $manager->getSessionForRequest( new \FauxRequest
);
796 $backend = \TestingAccessWrapper
::newFromObject( $session )->backend
;
797 $sessionId = $session->getSessionId();
798 $id = (string)$sessionId;
800 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
802 $manager->changeBackendId( $backend );
803 $this->assertSame( $sessionId, $session->getSessionId() );
804 $this->assertNotEquals( $id, (string)$sessionId );
805 $id = (string)$sessionId;
807 $this->assertSame( $sessionId, $manager->getSessionById( $id, true )->getSessionId() );
809 // Destruction of the session here causes the backend to be deregistered
813 $manager->changeBackendId( $backend );
814 $this->fail( 'Expected exception not thrown' );
815 } catch ( \InvalidArgumentException
$ex ) {
817 'Backend was not registered with this SessionManager', $ex->getMessage()
822 $manager->deregisterSessionBackend( $backend );
823 $this->fail( 'Expected exception not thrown' );
824 } catch ( \InvalidArgumentException
$ex ) {
826 'Backend was not registered with this SessionManager', $ex->getMessage()
830 $session = $manager->getSessionById( $id, true );
831 $this->assertSame( $sessionId, $session->getSessionId() );
834 public function testGenerateSessionId() {
835 $manager = $this->getManager();
837 $id = $manager->generateSessionId();
838 $this->assertTrue( SessionManager
::validateSessionId( $id ), "Generated ID: $id" );
841 public function testAutoCreateUser() {
842 global $wgGroupPermissions;
844 \ObjectCache
::$instances[__METHOD__
] = new TestBagOStuff();
845 $this->setMwGlobals( [ 'wgMainCacheType' => __METHOD__
] );
846 $this->setMwGlobals( [
847 'wgAuth' => new AuthPlugin
,
850 $this->stashMwGlobals( [ 'wgGroupPermissions' ] );
851 $wgGroupPermissions['*']['createaccount'] = true;
852 $wgGroupPermissions['*']['autocreateaccount'] = false;
854 // Replace the global singleton with one configured for testing
855 $manager = $this->getManager();
856 $reset = TestUtils
::setSessionManagerSingleton( $manager );
858 $logger = new \
TestLogger( true, function ( $m ) {
859 if ( substr( $m, 0, 15 ) === 'SessionBackend ' ) {
863 $m = str_replace( 'MediaWiki\Session\SessionManager::autoCreateUser: ', '', $m );
866 $manager->setLogger( $logger );
868 $session = SessionManager
::getGlobalSession();
870 // Can't create an already-existing user
871 $user = User
::newFromName( 'UTSysop' );
872 $id = $user->getId();
873 $this->assertFalse( $manager->autoCreateUser( $user ) );
874 $this->assertSame( $id, $user->getId() );
875 $this->assertSame( 'UTSysop', $user->getName() );
876 $this->assertSame( [], $logger->getBuffer() );
877 $logger->clearBuffer();
879 // Sanity check that creation works at all
880 $user = User
::newFromName( 'UTSessionAutoCreate1' );
881 $this->assertSame( 0, $user->getId(), 'sanity check' );
882 $this->assertTrue( $manager->autoCreateUser( $user ) );
883 $this->assertNotEquals( 0, $user->getId() );
884 $this->assertSame( 'UTSessionAutoCreate1', $user->getName() );
886 $user->getId(), User
::idFromName( 'UTSessionAutoCreate1', User
::READ_LATEST
)
889 [ LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ],
890 ], $logger->getBuffer() );
891 $logger->clearBuffer();
893 // Check lack of permissions
894 $wgGroupPermissions['*']['createaccount'] = false;
895 $wgGroupPermissions['*']['autocreateaccount'] = false;
896 $user = User
::newFromName( 'UTDoesNotExist' );
897 $this->assertFalse( $manager->autoCreateUser( $user ) );
898 $this->assertSame( 0, $user->getId() );
899 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
900 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
905 'user is blocked from this wiki, blacklisting',
907 ], $logger->getBuffer() );
908 $logger->clearBuffer();
910 // Check other permission
911 $wgGroupPermissions['*']['createaccount'] = false;
912 $wgGroupPermissions['*']['autocreateaccount'] = true;
913 $user = User
::newFromName( 'UTSessionAutoCreate2' );
914 $this->assertSame( 0, $user->getId(), 'sanity check' );
915 $this->assertTrue( $manager->autoCreateUser( $user ) );
916 $this->assertNotEquals( 0, $user->getId() );
917 $this->assertSame( 'UTSessionAutoCreate2', $user->getName() );
919 $user->getId(), User
::idFromName( 'UTSessionAutoCreate2', User
::READ_LATEST
)
922 [ LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ],
923 ], $logger->getBuffer() );
924 $logger->clearBuffer();
926 // Test account-creation block
928 $block = new \
Block( [
929 'address' => $anon->getName(),
931 'reason' => __METHOD__
,
932 'expiry' => time() +
100500,
933 'createAccount' => true,
936 $this->assertInstanceOf( 'Block', $anon->isBlockedFromCreateAccount(), 'sanity check' );
937 $reset2 = new \
ScopedCallback( [ $block, 'delete' ] );
938 $user = User
::newFromName( 'UTDoesNotExist' );
939 $this->assertFalse( $manager->autoCreateUser( $user ) );
940 $this->assertSame( 0, $user->getId() );
941 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
942 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
943 \ScopedCallback
::consume( $reset2 );
946 [ LogLevel
::DEBUG
, 'user is blocked from this wiki, blacklisting' ],
947 ], $logger->getBuffer() );
948 $logger->clearBuffer();
950 // Sanity check that creation still works
951 $user = User
::newFromName( 'UTSessionAutoCreate3' );
952 $this->assertSame( 0, $user->getId(), 'sanity check' );
953 $this->assertTrue( $manager->autoCreateUser( $user ) );
954 $this->assertNotEquals( 0, $user->getId() );
955 $this->assertSame( 'UTSessionAutoCreate3', $user->getName() );
957 $user->getId(), User
::idFromName( 'UTSessionAutoCreate3', User
::READ_LATEST
)
960 [ LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ],
961 ], $logger->getBuffer() );
962 $logger->clearBuffer();
964 // Test prevention by AuthPlugin
966 $oldWgAuth = $wgAuth;
967 $mockWgAuth = $this->getMock( 'AuthPlugin', [ 'autoCreate' ] );
968 $mockWgAuth->expects( $this->once() )->method( 'autoCreate' )
969 ->will( $this->returnValue( false ) );
970 $this->setMwGlobals( [
971 'wgAuth' => $mockWgAuth,
973 $user = User
::newFromName( 'UTDoesNotExist' );
974 $this->assertFalse( $manager->autoCreateUser( $user ) );
975 $this->assertSame( 0, $user->getId() );
976 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
977 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
978 $this->setMwGlobals( [
979 'wgAuth' => $oldWgAuth,
983 [ LogLevel
::DEBUG
, 'denied by AuthPlugin' ],
984 ], $logger->getBuffer() );
985 $logger->clearBuffer();
987 // Test prevention by wfReadOnly()
988 $this->setMwGlobals( [
989 'wgReadOnly' => 'Because',
991 $user = User
::newFromName( 'UTDoesNotExist' );
992 $this->assertFalse( $manager->autoCreateUser( $user ) );
993 $this->assertSame( 0, $user->getId() );
994 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
995 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
996 $this->setMwGlobals( [
997 'wgReadOnly' => false,
1000 $this->assertSame( [
1001 [ LogLevel
::DEBUG
, 'denied by wfReadOnly()' ],
1002 ], $logger->getBuffer() );
1003 $logger->clearBuffer();
1005 // Test prevention by a previous session
1006 $session->set( 'MWSession::AutoCreateBlacklist', 'test' );
1007 $user = User
::newFromName( 'UTDoesNotExist' );
1008 $this->assertFalse( $manager->autoCreateUser( $user ) );
1009 $this->assertSame( 0, $user->getId() );
1010 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
1011 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1013 $this->assertSame( [
1014 [ LogLevel
::DEBUG
, 'blacklisted in session (test)' ],
1015 ], $logger->getBuffer() );
1016 $logger->clearBuffer();
1018 // Test uncreatable name
1019 $user = User
::newFromName( 'UTDoesNotExist@' );
1020 $this->assertFalse( $manager->autoCreateUser( $user ) );
1021 $this->assertSame( 0, $user->getId() );
1022 $this->assertNotSame( 'UTDoesNotExist@', $user->getName() );
1023 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1025 $this->assertSame( [
1026 [ LogLevel
::DEBUG
, 'Invalid username, blacklisting' ],
1027 ], $logger->getBuffer() );
1028 $logger->clearBuffer();
1030 // Test AbortAutoAccount hook
1031 $mock = $this->getMock( __CLASS__
, [ 'onAbortAutoAccount' ] );
1032 $mock->expects( $this->once() )->method( 'onAbortAutoAccount' )
1033 ->will( $this->returnCallback( function ( User
$user, &$msg ) {
1037 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'AbortAutoAccount' => [ $mock ] ] );
1038 $user = User
::newFromName( 'UTDoesNotExist' );
1039 $this->assertFalse( $manager->autoCreateUser( $user ) );
1040 $this->assertSame( 0, $user->getId() );
1041 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
1042 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1043 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'AbortAutoAccount' => [] ] );
1045 $this->assertSame( [
1046 [ LogLevel
::DEBUG
, 'denied by hook: No way!' ],
1047 ], $logger->getBuffer() );
1048 $logger->clearBuffer();
1050 // Test AbortAutoAccount hook screwing up the name
1051 $mock = $this->getMock( 'stdClass', [ 'onAbortAutoAccount' ] );
1052 $mock->expects( $this->once() )->method( 'onAbortAutoAccount' )
1053 ->will( $this->returnCallback( function ( User
$user ) {
1054 $user->setName( 'UTDoesNotExistEither' );
1056 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'AbortAutoAccount' => [ $mock ] ] );
1058 $user = User
::newFromName( 'UTDoesNotExist' );
1059 $manager->autoCreateUser( $user );
1060 $this->fail( 'Expected exception not thrown' );
1061 } catch ( \UnexpectedValueException
$ex ) {
1063 'AbortAutoAccount hook tried to change the user name',
1067 $this->assertSame( 0, $user->getId() );
1068 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
1069 $this->assertNotSame( 'UTDoesNotExistEither', $user->getName() );
1070 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1071 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExistEither', User
::READ_LATEST
) );
1072 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'AbortAutoAccount' => [] ] );
1074 $this->assertSame( [], $logger->getBuffer() );
1075 $logger->clearBuffer();
1077 // Test for "exception backoff"
1078 $user = User
::newFromName( 'UTDoesNotExist' );
1079 $cache = \ObjectCache
::getLocalClusterInstance();
1080 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $user->getName() ) );
1081 $cache->set( $backoffKey, 1, 60 * 10 );
1082 $this->assertFalse( $manager->autoCreateUser( $user ) );
1083 $this->assertSame( 0, $user->getId() );
1084 $this->assertNotSame( 'UTDoesNotExist', $user->getName() );
1085 $this->assertEquals( 0, User
::idFromName( 'UTDoesNotExist', User
::READ_LATEST
) );
1086 $cache->delete( $backoffKey );
1088 $this->assertSame( [
1089 [ LogLevel
::DEBUG
, 'denied by prior creation attempt failures' ],
1090 ], $logger->getBuffer() );
1091 $logger->clearBuffer();
1093 // Sanity check that creation still works, and test completion hook
1094 $cb = $this->callback( function ( User
$user ) {
1095 $this->assertNotEquals( 0, $user->getId() );
1096 $this->assertSame( 'UTSessionAutoCreate4', $user->getName() );
1097 $this->assertEquals(
1098 $user->getId(), User
::idFromName( 'UTSessionAutoCreate4', User
::READ_LATEST
)
1102 $mock = $this->getMock( 'stdClass',
1103 [ 'onAuthPluginAutoCreate', 'onLocalUserCreated' ] );
1104 $mock->expects( $this->once() )->method( 'onAuthPluginAutoCreate' )
1106 $mock->expects( $this->once() )->method( 'onLocalUserCreated' )
1107 ->with( $cb, $this->identicalTo( true ) );
1108 $this->mergeMwGlobalArrayValue( 'wgHooks', [
1109 'AuthPluginAutoCreate' => [ $mock ],
1110 'LocalUserCreated' => [ $mock ],
1112 $user = User
::newFromName( 'UTSessionAutoCreate4' );
1113 $this->assertSame( 0, $user->getId(), 'sanity check' );
1114 $this->assertTrue( $manager->autoCreateUser( $user ) );
1115 $this->assertNotEquals( 0, $user->getId() );
1116 $this->assertSame( 'UTSessionAutoCreate4', $user->getName() );
1117 $this->assertEquals(
1119 User
::idFromName( 'UTSessionAutoCreate4', User
::READ_LATEST
)
1121 $this->mergeMwGlobalArrayValue( 'wgHooks', [
1122 'AuthPluginAutoCreate' => [],
1123 'LocalUserCreated' => [],
1125 $this->assertSame( [
1126 [ LogLevel
::INFO
, 'creating new user ({username}) - from: {url}' ],
1127 ], $logger->getBuffer() );
1128 $logger->clearBuffer();
1131 public function onAbortAutoAccount( User
$user, &$msg ) {
1134 public function testPreventSessionsForUser() {
1135 $manager = $this->getManager();
1137 $providerBuilder = $this->getMockBuilder( 'DummySessionProvider' )
1138 ->setMethods( [ 'preventSessionsForUser', '__toString' ] );
1140 $provider1 = $providerBuilder->getMock();
1141 $provider1->expects( $this->once() )->method( 'preventSessionsForUser' )
1142 ->with( $this->equalTo( 'UTSysop' ) );
1143 $provider1->expects( $this->any() )->method( '__toString' )
1144 ->will( $this->returnValue( 'MockProvider1' ) );
1146 $this->config
->set( 'SessionProviders', [
1147 $this->objectCacheDef( $provider1 ),
1150 $this->assertFalse( $manager->isUserSessionPrevented( 'UTSysop' ) );
1151 $manager->preventSessionsForUser( 'UTSysop' );
1152 $this->assertTrue( $manager->isUserSessionPrevented( 'UTSysop' ) );
1155 public function testLoadSessionInfoFromStore() {
1156 $manager = $this->getManager();
1157 $logger = new \
TestLogger( true );
1158 $manager->setLogger( $logger );
1159 $request = new \
FauxRequest();
1161 // TestingAccessWrapper can't handle methods with reference arguments, sigh.
1162 $rClass = new \
ReflectionClass( $manager );
1163 $rMethod = $rClass->getMethod( 'loadSessionInfoFromStore' );
1164 $rMethod->setAccessible( true );
1165 $loadSessionInfoFromStore = function ( &$info ) use ( $rMethod, $manager, $request ) {
1166 return $rMethod->invokeArgs( $manager, [ &$info, $request ] );
1169 $userInfo = UserInfo
::newFromName( 'UTSysop', true );
1170 $unverifiedUserInfo = UserInfo
::newFromName( 'UTSysop', false );
1172 $id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
1174 'userId' => $userInfo->getId(),
1175 'userName' => $userInfo->getName(),
1176 'userToken' => $userInfo->getToken( true ),
1177 'provider' => 'Mock',
1180 $builder = $this->getMockBuilder( SessionProvider
::class )
1181 ->setMethods( [ '__toString', 'mergeMetadata', 'refreshSessionInfo' ] );
1183 $provider = $builder->getMockForAbstractClass();
1184 $provider->setManager( $manager );
1185 $provider->expects( $this->any() )->method( 'persistsSessionId' )
1186 ->will( $this->returnValue( true ) );
1187 $provider->expects( $this->any() )->method( 'canChangeUser' )
1188 ->will( $this->returnValue( true ) );
1189 $provider->expects( $this->any() )->method( 'refreshSessionInfo' )
1190 ->will( $this->returnValue( true ) );
1191 $provider->expects( $this->any() )->method( '__toString' )
1192 ->will( $this->returnValue( 'Mock' ) );
1193 $provider->expects( $this->any() )->method( 'mergeMetadata' )
1194 ->will( $this->returnCallback( function ( $a, $b ) {
1195 if ( $b === [ 'Throw' ] ) {
1196 throw new MetadataMergeException( 'no merge!' );
1198 return [ 'Merged' ];
1201 $provider2 = $builder->getMockForAbstractClass();
1202 $provider2->setManager( $manager );
1203 $provider2->expects( $this->any() )->method( 'persistsSessionId' )
1204 ->will( $this->returnValue( false ) );
1205 $provider2->expects( $this->any() )->method( 'canChangeUser' )
1206 ->will( $this->returnValue( false ) );
1207 $provider2->expects( $this->any() )->method( '__toString' )
1208 ->will( $this->returnValue( 'Mock2' ) );
1209 $provider2->expects( $this->any() )->method( 'refreshSessionInfo' )
1210 ->will( $this->returnCallback( function ( $info, $request, &$metadata ) {
1211 $metadata['changed'] = true;
1215 $provider3 = $builder->getMockForAbstractClass();
1216 $provider3->setManager( $manager );
1217 $provider3->expects( $this->any() )->method( 'persistsSessionId' )
1218 ->will( $this->returnValue( true ) );
1219 $provider3->expects( $this->any() )->method( 'canChangeUser' )
1220 ->will( $this->returnValue( true ) );
1221 $provider3->expects( $this->once() )->method( 'refreshSessionInfo' )
1222 ->will( $this->returnValue( false ) );
1223 $provider3->expects( $this->any() )->method( '__toString' )
1224 ->will( $this->returnValue( 'Mock3' ) );
1226 \TestingAccessWrapper
::newFromObject( $manager )->sessionProviders
= [
1227 (string)$provider => $provider,
1228 (string)$provider2 => $provider2,
1229 (string)$provider3 => $provider3,
1232 // No metadata, basic usage
1233 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1234 'provider' => $provider,
1236 'userInfo' => $userInfo
1238 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1239 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1240 $this->assertFalse( $info->isIdSafe() );
1241 $this->assertSame( [], $logger->getBuffer() );
1243 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1244 'provider' => $provider,
1245 'userInfo' => $userInfo
1247 $this->assertTrue( $info->isIdSafe(), 'sanity check' );
1248 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1249 $this->assertTrue( $info->isIdSafe() );
1250 $this->assertSame( [], $logger->getBuffer() );
1252 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1253 'provider' => $provider2,
1255 'userInfo' => $userInfo
1257 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1258 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1259 $this->assertTrue( $info->isIdSafe() );
1260 $this->assertSame( [], $logger->getBuffer() );
1262 // Unverified user, no metadata
1263 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1264 'provider' => $provider,
1266 'userInfo' => $unverifiedUserInfo
1268 $this->assertSame( $unverifiedUserInfo, $info->getUserInfo() );
1269 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1270 $this->assertSame( [
1273 'Session "{session}": Unverified user provided and no metadata to auth it',
1275 ], $logger->getBuffer() );
1276 $logger->clearBuffer();
1278 // No metadata, missing data
1279 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1281 'userInfo' => $userInfo
1283 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1284 $this->assertSame( [
1285 [ LogLevel
::WARNING
, 'Session "{session}": Null provider and no metadata' ],
1286 ], $logger->getBuffer() );
1287 $logger->clearBuffer();
1289 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1290 'provider' => $provider,
1293 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1294 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1295 $this->assertInstanceOf( UserInfo
::class, $info->getUserInfo() );
1296 $this->assertTrue( $info->getUserInfo()->isVerified() );
1297 $this->assertTrue( $info->getUserInfo()->isAnon() );
1298 $this->assertFalse( $info->isIdSafe() );
1299 $this->assertSame( [], $logger->getBuffer() );
1301 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1302 'provider' => $provider2,
1305 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1306 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1307 $this->assertSame( [
1308 [ LogLevel
::INFO
, 'Session "{session}": No user provided and provider cannot set user' ]
1309 ], $logger->getBuffer() );
1310 $logger->clearBuffer();
1312 // Incomplete/bad metadata
1313 $this->store
->setRawSession( $id, true );
1314 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1315 $this->assertSame( [
1316 [ LogLevel
::WARNING
, 'Session "{session}": Bad data' ],
1317 ], $logger->getBuffer() );
1318 $logger->clearBuffer();
1320 $this->store
->setRawSession( $id, [ 'data' => [] ] );
1321 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1322 $this->assertSame( [
1323 [ LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ],
1324 ], $logger->getBuffer() );
1325 $logger->clearBuffer();
1327 $this->store
->deleteSession( $id );
1328 $this->store
->setRawSession( $id, [ 'metadata' => $metadata ] );
1329 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1330 $this->assertSame( [
1331 [ LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ],
1332 ], $logger->getBuffer() );
1333 $logger->clearBuffer();
1335 $this->store
->setRawSession( $id, [ 'metadata' => $metadata, 'data' => true ] );
1336 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1337 $this->assertSame( [
1338 [ LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ],
1339 ], $logger->getBuffer() );
1340 $logger->clearBuffer();
1342 $this->store
->setRawSession( $id, [ 'metadata' => true, 'data' => [] ] );
1343 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1344 $this->assertSame( [
1345 [ LogLevel
::WARNING
, 'Session "{session}": Bad data structure' ],
1346 ], $logger->getBuffer() );
1347 $logger->clearBuffer();
1349 foreach ( $metadata as $key => $dummy ) {
1351 unset( $tmp[$key] );
1352 $this->store
->setRawSession( $id, [ 'metadata' => $tmp, 'data' => [] ] );
1353 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1354 $this->assertSame( [
1355 [ LogLevel
::WARNING
, 'Session "{session}": Bad metadata' ],
1356 ], $logger->getBuffer() );
1357 $logger->clearBuffer();
1360 // Basic usage with metadata
1361 $this->store
->setRawSession( $id, [ 'metadata' => $metadata, 'data' => [] ] );
1362 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1363 'provider' => $provider,
1365 'userInfo' => $userInfo
1367 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1368 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1369 $this->assertTrue( $info->isIdSafe() );
1370 $this->assertSame( [], $logger->getBuffer() );
1372 // Mismatched provider
1373 $this->store
->setSessionMeta( $id, [ 'provider' => 'Bad' ] +
$metadata );
1374 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1375 'provider' => $provider,
1377 'userInfo' => $userInfo
1379 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1380 $this->assertSame( [
1381 [ LogLevel
::WARNING
, 'Session "{session}": Wrong provider Bad !== Mock' ],
1382 ], $logger->getBuffer() );
1383 $logger->clearBuffer();
1386 $this->store
->setSessionMeta( $id, [ 'provider' => 'Bad' ] +
$metadata );
1387 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1389 'userInfo' => $userInfo
1391 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1392 $this->assertSame( [
1393 [ LogLevel
::WARNING
, 'Session "{session}": Unknown provider Bad' ],
1394 ], $logger->getBuffer() );
1395 $logger->clearBuffer();
1398 $this->store
->setSessionMeta( $id, $metadata );
1399 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1401 'userInfo' => $userInfo
1403 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1404 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1405 $this->assertTrue( $info->isIdSafe() );
1406 $this->assertSame( [], $logger->getBuffer() );
1408 // Bad user metadata
1409 $this->store
->setSessionMeta( $id, [ 'userId' => -1, 'userToken' => null ] +
$metadata );
1410 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1411 'provider' => $provider,
1414 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1415 $this->assertSame( [
1416 [ LogLevel
::ERROR
, 'Session "{session}": {exception}' ],
1417 ], $logger->getBuffer() );
1418 $logger->clearBuffer();
1420 $this->store
->setSessionMeta(
1421 $id, [ 'userId' => 0, 'userName' => '<X>', 'userToken' => null ] +
$metadata
1423 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1424 'provider' => $provider,
1427 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1428 $this->assertSame( [
1429 [ LogLevel
::ERROR
, 'Session "{session}": {exception}', ],
1430 ], $logger->getBuffer() );
1431 $logger->clearBuffer();
1433 // Mismatched user by ID
1434 $this->store
->setSessionMeta(
1435 $id, [ 'userId' => $userInfo->getId() +
1, 'userToken' => null ] +
$metadata
1437 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1438 'provider' => $provider,
1440 'userInfo' => $userInfo
1442 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1443 $this->assertSame( [
1444 [ LogLevel
::WARNING
, 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}' ],
1445 ], $logger->getBuffer() );
1446 $logger->clearBuffer();
1448 // Mismatched user by name
1449 $this->store
->setSessionMeta(
1450 $id, [ 'userId' => 0, 'userName' => 'X', 'userToken' => null ] +
$metadata
1452 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1453 'provider' => $provider,
1455 'userInfo' => $userInfo
1457 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1458 $this->assertSame( [
1459 [ LogLevel
::WARNING
, 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}' ],
1460 ], $logger->getBuffer() );
1461 $logger->clearBuffer();
1463 // ID matches, name doesn't
1464 $this->store
->setSessionMeta(
1465 $id, [ 'userId' => $userInfo->getId(), 'userName' => 'X', 'userToken' => null ] +
$metadata
1467 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1468 'provider' => $provider,
1470 'userInfo' => $userInfo
1472 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1473 $this->assertSame( [
1476 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}'
1478 ], $logger->getBuffer() );
1479 $logger->clearBuffer();
1481 // Mismatched anon user
1482 $this->store
->setSessionMeta(
1483 $id, [ 'userId' => 0, 'userName' => null, 'userToken' => null ] +
$metadata
1485 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1486 'provider' => $provider,
1488 'userInfo' => $userInfo
1490 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1491 $this->assertSame( [
1494 'Session "{session}": Metadata has an anonymous user, ' .
1495 'but a non-anon user was provided',
1497 ], $logger->getBuffer() );
1498 $logger->clearBuffer();
1500 // Lookup user by ID
1501 $this->store
->setSessionMeta( $id, [ 'userToken' => null ] +
$metadata );
1502 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1503 'provider' => $provider,
1506 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1507 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1508 $this->assertSame( $userInfo->getId(), $info->getUserInfo()->getId() );
1509 $this->assertTrue( $info->isIdSafe() );
1510 $this->assertSame( [], $logger->getBuffer() );
1512 // Lookup user by name
1513 $this->store
->setSessionMeta(
1514 $id, [ 'userId' => 0, 'userName' => 'UTSysop', 'userToken' => null ] +
$metadata
1516 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1517 'provider' => $provider,
1520 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1521 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1522 $this->assertSame( $userInfo->getId(), $info->getUserInfo()->getId() );
1523 $this->assertTrue( $info->isIdSafe() );
1524 $this->assertSame( [], $logger->getBuffer() );
1526 // Lookup anonymous user
1527 $this->store
->setSessionMeta(
1528 $id, [ 'userId' => 0, 'userName' => null, 'userToken' => null ] +
$metadata
1530 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1531 'provider' => $provider,
1534 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1535 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1536 $this->assertTrue( $info->getUserInfo()->isAnon() );
1537 $this->assertTrue( $info->isIdSafe() );
1538 $this->assertSame( [], $logger->getBuffer() );
1540 // Unverified user with metadata
1541 $this->store
->setSessionMeta( $id, $metadata );
1542 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1543 'provider' => $provider,
1545 'userInfo' => $unverifiedUserInfo
1547 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1548 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1549 $this->assertTrue( $info->getUserInfo()->isVerified() );
1550 $this->assertSame( $unverifiedUserInfo->getId(), $info->getUserInfo()->getId() );
1551 $this->assertSame( $unverifiedUserInfo->getName(), $info->getUserInfo()->getName() );
1552 $this->assertTrue( $info->isIdSafe() );
1553 $this->assertSame( [], $logger->getBuffer() );
1555 // Unverified user with metadata
1556 $this->store
->setSessionMeta( $id, $metadata );
1557 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1558 'provider' => $provider,
1560 'userInfo' => $unverifiedUserInfo
1562 $this->assertFalse( $info->isIdSafe(), 'sanity check' );
1563 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1564 $this->assertTrue( $info->getUserInfo()->isVerified() );
1565 $this->assertSame( $unverifiedUserInfo->getId(), $info->getUserInfo()->getId() );
1566 $this->assertSame( $unverifiedUserInfo->getName(), $info->getUserInfo()->getName() );
1567 $this->assertTrue( $info->isIdSafe() );
1568 $this->assertSame( [], $logger->getBuffer() );
1571 $this->store
->setSessionMeta( $id, [ 'userToken' => 'Bad' ] +
$metadata );
1572 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1573 'provider' => $provider,
1575 'userInfo' => $userInfo
1577 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1578 $this->assertSame( [
1579 [ LogLevel
::WARNING
, 'Session "{session}": User token mismatch' ],
1580 ], $logger->getBuffer() );
1581 $logger->clearBuffer();
1583 // Provider metadata
1584 $this->store
->setSessionMeta( $id, [ 'provider' => 'Mock2' ] +
$metadata );
1585 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1586 'provider' => $provider2,
1588 'userInfo' => $userInfo,
1589 'metadata' => [ 'Info' ],
1591 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1592 $this->assertSame( [ 'Info', 'changed' => true ], $info->getProviderMetadata() );
1593 $this->assertSame( [], $logger->getBuffer() );
1595 $this->store
->setSessionMeta( $id, [ 'providerMetadata' => [ 'Saved' ] ] +
$metadata );
1596 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1597 'provider' => $provider,
1599 'userInfo' => $userInfo,
1601 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1602 $this->assertSame( [ 'Saved' ], $info->getProviderMetadata() );
1603 $this->assertSame( [], $logger->getBuffer() );
1605 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1606 'provider' => $provider,
1608 'userInfo' => $userInfo,
1609 'metadata' => [ 'Info' ],
1611 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1612 $this->assertSame( [ 'Merged' ], $info->getProviderMetadata() );
1613 $this->assertSame( [], $logger->getBuffer() );
1615 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1616 'provider' => $provider,
1618 'userInfo' => $userInfo,
1619 'metadata' => [ 'Throw' ],
1621 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1622 $this->assertSame( [
1625 'Session "{session}": Metadata merge failed: {exception}',
1627 ], $logger->getBuffer() );
1628 $logger->clearBuffer();
1630 // Remember from session
1631 $this->store
->setSessionMeta( $id, $metadata );
1632 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1633 'provider' => $provider,
1636 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1637 $this->assertFalse( $info->wasRemembered() );
1638 $this->assertSame( [], $logger->getBuffer() );
1640 $this->store
->setSessionMeta( $id, [ 'remember' => true ] +
$metadata );
1641 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1642 'provider' => $provider,
1645 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1646 $this->assertTrue( $info->wasRemembered() );
1647 $this->assertSame( [], $logger->getBuffer() );
1649 $this->store
->setSessionMeta( $id, [ 'remember' => false ] +
$metadata );
1650 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1651 'provider' => $provider,
1653 'userInfo' => $userInfo
1655 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1656 $this->assertTrue( $info->wasRemembered() );
1657 $this->assertSame( [], $logger->getBuffer() );
1659 // forceHTTPS from session
1660 $this->store
->setSessionMeta( $id, $metadata );
1661 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1662 'provider' => $provider,
1664 'userInfo' => $userInfo
1666 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1667 $this->assertFalse( $info->forceHTTPS() );
1668 $this->assertSame( [], $logger->getBuffer() );
1670 $this->store
->setSessionMeta( $id, [ 'forceHTTPS' => true ] +
$metadata );
1671 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1672 'provider' => $provider,
1674 'userInfo' => $userInfo
1676 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1677 $this->assertTrue( $info->forceHTTPS() );
1678 $this->assertSame( [], $logger->getBuffer() );
1680 $this->store
->setSessionMeta( $id, [ 'forceHTTPS' => false ] +
$metadata );
1681 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1682 'provider' => $provider,
1684 'userInfo' => $userInfo,
1685 'forceHTTPS' => true
1687 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1688 $this->assertTrue( $info->forceHTTPS() );
1689 $this->assertSame( [], $logger->getBuffer() );
1691 // "Persist" flag from session
1692 $this->store
->setSessionMeta( $id, $metadata );
1693 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1694 'provider' => $provider,
1696 'userInfo' => $userInfo
1698 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1699 $this->assertFalse( $info->wasPersisted() );
1700 $this->assertSame( [], $logger->getBuffer() );
1702 $this->store
->setSessionMeta( $id, [ 'persisted' => true ] +
$metadata );
1703 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1704 'provider' => $provider,
1706 'userInfo' => $userInfo
1708 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1709 $this->assertTrue( $info->wasPersisted() );
1710 $this->assertSame( [], $logger->getBuffer() );
1712 $this->store
->setSessionMeta( $id, [ 'persisted' => false ] +
$metadata );
1713 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1714 'provider' => $provider,
1716 'userInfo' => $userInfo,
1719 $this->assertTrue( $loadSessionInfoFromStore( $info ) );
1720 $this->assertTrue( $info->wasPersisted() );
1721 $this->assertSame( [], $logger->getBuffer() );
1723 // Provider refreshSessionInfo() returning false
1724 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1725 'provider' => $provider3,
1727 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1728 $this->assertSame( [], $logger->getBuffer() );
1732 $data = [ 'foo' => 1 ];
1733 $this->store
->setSession( $id, [ 'metadata' => $metadata, 'data' => $data ] );
1734 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [
1735 'provider' => $provider,
1737 'userInfo' => $userInfo
1739 $this->mergeMwGlobalArrayValue( 'wgHooks', [
1740 'SessionCheckInfo' => [ function ( &$reason, $i, $r, $m, $d ) use (
1741 $info, $metadata, $data, $request, &$called
1743 $this->assertSame( $info->getId(), $i->getId() );
1744 $this->assertSame( $info->getProvider(), $i->getProvider() );
1745 $this->assertSame( $info->getUserInfo(), $i->getUserInfo() );
1746 $this->assertSame( $request, $r );
1747 $this->assertEquals( $metadata, $m );
1748 $this->assertEquals( $data, $d );
1753 $this->assertFalse( $loadSessionInfoFromStore( $info ) );
1754 $this->assertTrue( $called );
1755 $this->assertSame( [
1756 [ LogLevel
::WARNING
, 'Session "{session}": Hook aborted' ],
1757 ], $logger->getBuffer() );
1758 $logger->clearBuffer();